using System;
using System.Linq;
using System.Data;
using System.Data.Entity;

namespace Caramel.EntityFramework
{
	public class EntityFrameworkRepository<T> : IRepository<T> where T : class
	{
		public DbContext Context
		{
			get
			{
				if (UnitOfWork.Current == null)
				{
					throw new InvalidOperationException("No unit of work exists for the operation.");
				}

				if (!(UnitOfWork.Current is IEntityFrameworkUnitOfWork))
				{
					throw new InvalidOperationException(String.Format("Current unit of work does not implement {0}.", typeof(IEntityFrameworkUnitOfWork).Name));
				}

				return ((IEntityFrameworkUnitOfWork)UnitOfWork.Current).Context;
			}
		}

		#region IRepository<T> Members

		public T Get(object id)
		{
			return this.Context.Set<T>().Find(id);
		}

		public void Save(T entity)
		{
			if ((this.Context.Entry<T>(entity).State == EntityState.Added) || (this.Context.Entry<T>(entity).State == EntityState.Detached))
			{
				this.Context.Set<T>().Add(entity);
			}
		}

		public void Delete(T entity)
		{
			this.Context.Set<T>().Remove(entity);
		}

		public void DeleteAll()
		{
			// This can't be right, need to revisit...
			foreach (var entity in this.Context.Set<T>())
			{
				this.Context.Set<T>().Remove(entity);
			}
		}

		public IQueryable<T> All
		{
			get
			{
				return this.Context.Set<T>().AsQueryable();
			}
		}

		#endregion
	}
}
